package cn.edu.njuit.webserver.securityserver.filter;


import cn.edu.njuit.webserver.securityserver.service.CurrentUser;
import cn.edu.njuit.webserver.securityserver.service.TokenService;
import cn.edu.njuit.webserver.securityserver.service.dto.UserToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: TODO
 * @Data: 2022/8/30 10:15
 * @Author: guzy
 */

@WebFilter(urlPatterns = "/api/sys/*")
public class RequestFilter implements Filter {
    @Autowired
    @Qualifier("JwtTokenService")
    TokenService tokenService;

    Logger logger = LoggerFactory.getLogger(RequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("我是拦截器");
        //从头部(token)获取令牌
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("Authorization");
        //没有token
        if (token == null) {
            //拒绝请求
            logger.error("没有令牌，不让访问");
            return;
        }
        //有令牌，通过
        if (!tokenService.validateToken(token)) {
            logger.error("令牌不合法，不让访问");
            return;
        }

        String login = tokenService.getLogin(token);
        UserToken user = null;
        try {
            user = tokenService.getUser(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        logger.info("从令牌中获取的登录信息：" + user);

        // 将当前用户存储到当前线程变量中
        CurrentUser.CURRENTUSERTOKEN.set(user);

        // 释放到下一个环节
        filterChain.doFilter(servletRequest, servletResponse);

        //清空当前线程变量
        CurrentUser.CURRENTUSERTOKEN.remove();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
